<template>
	<view class="container">
		<image v-if="imageUrl" :src="imageUrl" style="width: 600rpx; height: 600rpx;" mode=""></image>
		<camera v-else device-position="front" flash="off" style="width: 600rpx; height: 600rpx;"></camera>
	</view>
</template>

<script lang="ts" setup>
	import { ref } from 'vue'
	import api from '@/api'
	import config from '@/config/index.ts'
	import { onLoad } from '@dcloudio/uni-app'
	const detail = ref({
		realName: '',
		idCard: '',
		selectOpeningType: '',
		deposit: ''
	})
	onLoad((e) => {
		detail.value = JSON.parse(e.detail)
		setTimeout(() => {
			takePhoto()
		}, 5000)
	})

	const imageUrl = ref<string>('')
	const takePhoto = () => {
		const ctx = uni.createCameraContext();
		ctx.takePhoto({
			quality: 'high',
			success: async (res : any) => {
				console.log(res,66)
				let imgFile = res.tempImagePath.replace('.png', '.jpg')
				console.log("imgFile",imgFile)
				uni.uploadFile({
					url: config.api + '/api/mall/user/uploadFacePic',
					filePath: imgFile,
					name: 'file',
					header: {
						'x-flow-id': new Date().getTime(),
					},
					formData: {
						'user': 'test'
					},
					success: (uploadFileRes) => {
						console.log(uploadFileRes)
						imageUrl.value = JSON.parse(uploadFileRes.data).data
						console.log(imageUrl.value,'666')
						submit()
					}
				})  
				// uni.compressImage({
				// 	src: res.tempImagePath.replace('.png', '.jpg'), // 图片路径
				// 	quality: 80, // 压缩质量，范围为0 - 100，100为不压缩
				// 	success: (compressRes) => {
				// 		console.log('压缩成功', compressRes);
				// 		// 处理compressRes.tempFilePath即为压缩后的图片路径
						
				// 	},
				// 	fail: (err) => {
				// 		console.log('压缩失败', err);
				// 	}
				// });
			}
		});
	}
	const submit = async () => {
		const res2 : any = await api({
			method: 'post',
			url: `/mall/user/nameAuthenticate`,
			data: {
				realName: detail.value.realName,
				idCard: detail.value.idCard,
				facialPictureUrl: imageUrl.value
			}
		})
		if (res2) {
			uni.showToast({
				title: res2.data ? '实名认证成功' : '识别失败，请检查',
				icon: 'none'
			})
			setTimeout(() => {
				if (res2.data) {
					let url = detail.value.selectOpeningType == '1' && Number(detail.value.deposit) ? 'payment/payment' : 'openStudio/openStudio'
					uni.redirectTo({
						url: `/pages/applyLookAfterPet/${url}?deposit=` + detail.value.deposit + '&selectOpeningType=' + detail.value.selectOpeningType
					})
				} else {
					uni.navigateBack()
				}

			}, 1200)
		}
	}
	const error = (e) => {
		console.log(e.detail);
		uni.showToast({
			title: '请打开摄像头，才能完成实名认证',
			icon: 'none'
		})
	}
</script>

<style lang="scss" scoped>

</style>